package com.itheima.commons.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class UploadPicUtil {
    private UploadPicUtil() {
    }

    private static String endpoint;
    private static String accessKeyId;
    private static String accessKeySecret;
    private static String picurl;

    static {
        Properties properties = new Properties();
        try {
            properties.load(SendSMSUtil.class.getClassLoader().getResourceAsStream("aliyun.properties"));
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            endpoint = properties.getProperty("oss.endpoint");
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            accessKeyId = properties.getProperty("oss.access_key_id");
            accessKeySecret = properties.getProperty("oss.access_key_secret");
            picurl = properties.getProperty("oss.picurl");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String uploadPic(String fileName,byte[] imageData) {

        // 填写Bucket名称，例如examplebucket。
        // 填写文件名。文件名包含路径，不包含Bucket名称。例如exampledir/exampleobject.txt。
        //String objectName = "exampledir/exampleobject.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String content = "Hello OSS";
        String filePath = dateTime(fileName);
        ossClient.putObject("cdbtanhua", filePath, new ByteArrayInputStream(imageData));

        // 关闭OSSClient。
        ossClient.shutdown();
        return picurl+filePath;
    }

    public static String dateTime(String fileName){
        DateTime dateTime = new DateTime();
        return "images/"+dateTime.toString("yyyy")+"/"
                +dateTime.toString("MM")+"/"+dateTime.toString("dd")
                +"/"+ UUID.randomUUID().toString() +fileName;

    }
}
